const Student = require("./Student")
const Teacher = require("./Teacher")
const User = require("./User")
const Employment = require("./Employment")
const Class = require('./Class')
const Course = require('./Course')
const Resource = require('./Resource')
const DefaultConfig = require('../config/default.config')


const Models = {
  Student,
  Teacher,
  User,
  Employment,
  Class,
  Course,
  Resource,

  // 初始化功能函数
  init: async function () {


    // 教师、学生、用户账户表关联
    User.hasOne(Student, { sourceKey: 'id', })
    Student.belongsTo(User)

    User.hasOne(Teacher, { sourceKey: 'id' })
    Teacher.belongsTo(User)


    // 学生、就业情况表关联
    Student.hasOne(Employment, { sourceKey: 'UserId' })
    Employment.belongsTo(Student)


    // 学生、班级表关联
    Class.hasMany(Student, { sourceKey: 'id' })
    Student.belongsTo(Class)


    // 课程、班级、教室表关联
    Teacher.hasMany(Course, { sourceKey: 'UserId' })
    Course.belongsTo(Teacher)

    Class.hasMany(Course, { sourceKey: 'id' })
    Course.belongsTo(Class)


    // 课程、教学资源表关联
    Course.hasMany(Resource, { sourceKey: 'ClassId' })
    Resource.belongsTo(Course)



    // 表同步

    // 由于外键存在, 不要随意对调建表顺序
    // 源表: 无需任何表依赖
    await Class.sync()
    await User.sync()

    // 学生表:依赖User表、Class表
    await Student.sync()

    // 教师表: 依赖User表
    await Teacher.sync()

    // 课程表: 依赖Class表 teacher表
    await Course.sync()

    // 课程资源表: 依赖Course表
    await Resource.sync()

    // 就业信息表: 依赖Student表
    await Employment.sync()

    // 初始化管理员账号
    await User.generateAdmin(DefaultConfig.Admin)
  }
}

module.exports = Models